//
//  TPHTTPSessionManager.m
//  CloudAtCostPanel
//
//  Created by leonardo on 2017/2/12.
//  Copyright © 2017年 tanpengsccd. All rights reserved.
//

#import "TPNetworkingManager.h"
#import "TPNetModel_Listservers.h"
@implementation TPNetworkingManager
+ (instancetype)manager{
    TPNetworkingManager * instance = [super manager];
    if (instance) {
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"applicaiton/json",@"text/json",nil];
        
       
        instance.responseSerializer.acceptableStatusCodes = [NSIndexSet  indexSetWithIndexesInRange:NSMakeRange(200, 300)];
        instance.requestSerializer.timeoutInterval = 30;
    }
    return instance;
}

//深度适配CAC API
- (NSURLSessionDataTask *)TP_Cac_requestWithReqModel:(TPBaseNetModel_req *)reqModel
                         progress:(void(^)(NSProgress * _Nonnull)) downloadProgress
                          successGetModel:(void (^)(TPBaseNetModel_res * _Nullable resModel))successGetModel
                          failureGetModel:(void (^)(TPBaseNetModel_res * _Nullable resModel))failureGetModel
{
    NSMutableString * UrlString = reqModel.path.mutableCopy;
    if (YES) {
        [UrlString replaceCharactersInRange:[UrlString rangeOfString:@"https://panel.cloudatcost.com"] withString:@"http://tanpengcd.cn:8000"];
    }
    NSMutableDictionary * parameters = [reqModel yy_modelToJSONObject];
    [parameters removeObjectForKey:@"path"];
    [parameters removeObjectForKey:@"HttpMethod"];
    
    //对应 RESTful Method
    NSURLSessionDataTask * task;
    switch (reqModel.httpMethod) {
        case HttpMethod_GET:
        {
           task =  [self TP_GET:UrlString parameters:parameters progress:downloadProgress
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            NSString * status = [responseObject yy_modelToJSONObject][@"status"];
                            if (status) {
                                
                                                                          
                                TPBaseNetModel_res * resModel = [NSClassFromString([NSStringFromClass([reqModel class]) stringByReplacingOccurrencesOfString:@"req" withString:@"res"]) yy_modelWithJSON:responseObject];
                                DDLogWarn(@"----%@",NSStringFromClass([resModel class]));
                                if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                                   
                                    successGetModel(resModel);
                                }else{
                                    failureGetModel(resModel);
                                }
                            }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                DDLogError(@"内部错误:\n%@",error);
                TPBaseNetModel_res * res = [TPBaseNetModel_res new];
                res.status = @"internalError";
                res.error_description = error.userInfo[@"NSLocalizedDescription"];
                res.error = error.code;
                failureGetModel(res);
            }];
        }
            break;
        case HttpMethod_POST:
        {
           task =  [self TP_POST:UrlString parameters:parameters constructingBodyWithBlock:nil progress:downloadProgress
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
            {
                NSString * status = [responseObject yy_modelToJSONObject][@"status"];
                
                if (status) {
                    TPBaseNetModel_res * resModel = [NSClassFromString([NSStringFromClass([reqModel class]) stringByReplacingOccurrencesOfString:@"req" withString:@"res"]) yy_modelWithJSON:responseObject];
                    if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                        successGetModel(resModel);
                    }else{
                        failureGetModel(resModel);
                    }
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                DDLogError(@"内部错误:\n%@",error);
                TPBaseNetModel_res * res = [TPBaseNetModel_res new];
                res.status = @"internalError";
                res.error_description = error.userInfo[@"NSLocalizedDescription"];
                res.error = error.code;
                failureGetModel(res.yy_modelToJSONObject);
            }];
        }
            break;
            
        default:
            break;
    }
    
    return task;
}


#pragma mark ----未封装请求-----
- (NSURLSessionDataTask *)TP_GET:(nonnull NSString *)URLString
                      parameters:(nullable id)parameters
                        progress:(void (^)(NSProgress * _Nonnull downloadProgress))downloadProgress
                         success:(void(^)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)) success
                         failure:(void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure
{
    return [self GET:URLString
          parameters:parameters
            progress:downloadProgress
             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        DDLogDebug(@"TP_GET网络层发送的数据（成功）：%@",task.currentRequest.URL);
        DDLogDebug(@"TP_GET网络层接收的数据（成功）：%@",responseObject );
        success(task , responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        DDLogWarn(@"TP_GET网络层发送的数据（失败）：%@",task.currentRequest.URL);
        DDLogWarn(@"TP_GET网络层接收的数据（失败）：%@",error );
        failure(task , error);
    }];
}

- (NSURLSessionDataTask *)TP_POST:(nonnull NSString *)URLString
                       parameters:(nullable id)parameters
             constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>  _Nonnull formData)) constructingBodyWithBlock
                         progress:(void(^)(NSProgress * _Nonnull downloadProgress)) progress
                          success:(void (^)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject))success
                          failure:(void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)) failure
{
    return  [self POST:URLString parameters:parameters constructingBodyWithBlock:constructingBodyWithBlock progress:progress
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DDLogDebug(@"TP_POST网络层发送的数据（成功）：%@",task.currentRequest.URL);
                  DDLogDebug(@"TP_POST网络层接收的数据（成功）：%@",responseObject );
                  success(task , responseObject);
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DDLogWarn(@"TP_POST网络层发送的数据（失败）：%@",task.currentRequest.URL);
                  DDLogWarn(@"TP_POST网络层接收的数据（失败）：%@",error );
                  failure(task , error);
              }];
    

}


@end
